﻿using UnityEngine;
using System.Collections;
/// <summary>
/// 接收服务器的消息 ，并在此解决粘包和断包的问题
/// </summary>
/// 
public delegate void ReadSocketDataEventHandler(ByteBuf byteBuf);
public class ReadSocketDataManager
{

    //接收数据的缓存，即接收的数据包最大数据量
    private readonly ByteBuf receiveBuff = new ByteBuf(1024 * 1024);
    private readonly XinyueSocketClient socketClient;
    public event ReadSocketDataEventHandler ReadSocketDataEventHandler;

    public ReadSocketDataManager(XinyueSocketClient socketClient)
    {
        this.socketClient = socketClient;
        this.socketClient.ReceiveSocketDataHandler += OnReadSocket;
    }

    /// <summary>
    /// 接收socket信息，并做断包，粘包处理
    /// </summary>
    /// <param name="data"></param>
    public void OnReadSocket(byte[] data)
    {
        if (data.Length > 0)
        {
            if (!receiveBuff.IsWriteable(data.Length))
            {
                receiveBuff.DiscardReadBytes();
            }
            if (!receiveBuff.IsWriteable(data.Length))
            {
                Debug.LogWarning("服务器发送的数据包太大，超过客户端缓存，临时扩容");
               
            }
            receiveBuff.WriteBytes(data);
        }
        //循环读取缓存，因为可能会缓存多个TCP的数据包
        while (true && receiveBuff.ReadableBytes() >= 4)
        {
            receiveBuff.MarkReaderIndex();
            int messageLength = receiveBuff.ReadInt();
            //这里减4是因为它包括了包长自己占的消息位数
            int bodyLength = messageLength - 4;
            if (receiveBuff.ReadableBytes() >= bodyLength)
            {
                receiveBuff.ResetReaderIndex();
                ReadSocketDataEventHandler?.Invoke(receiveBuff);
            }
            else
            {
                //不足一个包的数据，等待下回接收的消息
                receiveBuff.ResetReaderIndex();
                break;
            }
        }

    }
}
